<template>
  <openlayer-base-map class="alarm_gis_map" ref="refOpenlayerBaseMap" :currentPageType="'alarm_gis_map'"
    :isControlOverviewInfo="true" :isAutoRenderData="true" :isShowLend="false" @getOlMapInstance="getOlMapInstance"
    @getCurrentViewData="getCurrentViewData" @reflashMap="reflashMap" @toggleOverviewInfo="toggleOverviewInfo"
    :key="Math.random()">

    <!-- <el-button type="primary" @click="reflashMap" class="reflash_map">刷新地图</el-button> -->

    <!-- 搜索组件 -->
    <map-search />

    <!-- 右侧信息 - 健康度概览 -->
    <health-overview v-show="isShowHealthOverview" />
  </openlayer-base-map>
</template>

<script setup name="alarmGis">
// vue - core
import { ref, onUnmounted, nextTick } from "vue";
import { useRoute } from "vue-router";
// 组件
import OpenlayerBaseMap from "@/components/OpenlayerBaseMap/index.vue";
import MapSearch from "./components/map-search/index.vue"; // 搜索组件
import HealthOverview from "./components/HealthOverview.vue"; // 健康度概览
import { getPopupInnerDom, getPOIPopupInnerDom, getFeaturesPopupInnerDom, getNoFeaturesPopupInnerDom } from "./components/popup/gisPopup.jsx"; // 气泡窗dom
// 工具
import mittBus from "@/utils/mittBus"; // mitt - 组件传参工具
import { gisDataStore } from '@/store/modules/gis.js'  // store
// api相关 - 工具
import { apiCommon, objIsEmpty, formatDate } from "@/utils/index.js";
import * as gisApi from "@/api/biz/maintenance";
// svg
// import POIPoint from "./icon/POIPoint.svg";
import alarmPoint from "./icon/alarmPoint.svg";

import { fromLonLat } from 'ol/proj';

const { proxy } = getCurrentInstance();
const gisStoreData = gisDataStore()

// 路由相关
const route = useRoute();

// 地图相关
const refOpenlayerBaseMap = ref(null); // 地图核心元素
let myOlMap = null;
let myMapCommonData = null;

// 业务数据
let currentContactType = "all"; // 当前网络制式
let currentSerious = "all"; // 当前基站类型
let currentRenderType = "频率"; // 当前渲染方式

let isShowHealthOverview = ref(true)

let allCurrentData = []

// 路由跳转参数
// let queryObj = null;  // 需要全局使用时解开

/**
 * 接收路由跳转参数
 */
const getQuery = () => {
  // 判断是否有参数
  if (objIsEmpty(route.query)) {
    return;
  }

  const { cgi } = route.query;

  // 根据cgi查询
  searchByCGIAsync(cgi); // 根据cgi搜索详情
};

/**
 * 接收其他组件派发的方法
 */
/**
 * 气泡窗
 */
//  修改通用展示窗数据
mittBus.on("fixCommonPopupData", (popupObj) => {
  // console.log("修改通用展示窗数据", popupObj);

  switch (popupObj.popupData.networkType) {
    case "4g":
      popupObj.popupData.newCellName = popupObj.popupData.cellName;
      break;
    case "5g":
      popupObj.popupData.newCellName = popupObj.popupData.nrCellName;
      break;
  }
});
// 设置通用气泡窗html
mittBus.on("setCommonPopupInner", ({ popupObj, featureItem, callback }) => {
  // console.log("设置通用气泡窗html", popupObj, featureItem);

  if (!featureItem) {
    let currentPopupData = popupObj.currentPopupData
    if (!currentPopupData) {
      currentPopupData = popupObj.popupData
    }
    if (currentPopupData.searchType === 'POI') {
      callback(getPOIPopupInnerDom(popupObj));
      return
    }
    callback(getPopupInnerDom(popupObj));
    return
  }

  if (featureItem.get('businessType') === 'POIMarker') {
    callback(getPOIPopupInnerDom(popupObj));
    return
  }
  callback(getPopupInnerDom(popupObj));
});
// 设置重叠要素气泡窗html
mittBus.on('setFeaturesPopupInner', ({ popupObj, callback, next }) => {
  // console.log(popupObj, callback, next)

  if (!popupObj.noFeature) {
    callback(getFeaturesPopupInnerDom(popupObj, currentDataList => {
      next(currentDataList)
    }));
  } else {
    callback(getNoFeaturesPopupInnerDom(popupObj, currentDataList => {
      // console.log(currentDataList)
      next(currentDataList)
    }));
  }
})
//  气泡窗点击更多 - 子组件使用
mittBus.on("popupDataGetMore", async ({ currentPopupObj, callback }) => {
  // console.log("气泡窗点击更多111", currentPopupObj);

  if (!currentPopupObj.currentPopupData && currentPopupObj.popupData) {
    currentPopupObj.currentPopupData = currentPopupObj.popupData
  }

  if (!currentPopupObj.currentPopupData) {
    currentPopupObj.currentPopupData = currentPopupObj
  }

  // 或者走接口,根据cgi获取详情
  const currentPopupAsyncObj = await apiCommon(gisApi.queryRealTimeAlarmByAlarmId, {
    alarmId: currentPopupObj.currentPopupData.alarmId,
  });
  // console.log(currentPopupAsyncObj)

  if (!currentPopupAsyncObj.data) {
    proxy.$modal.msgWarning(currentPopupAsyncObj.msg);
    return
  }

  // 处理数据 - 新增经纬度信息
  currentPopupAsyncObj.data.latitude = currentPopupObj.currentPopupData.latitude
  currentPopupAsyncObj.data.longitude = currentPopupObj.currentPopupData.longitude
  currentPopupAsyncObj.data.networkType = currentPopupObj.currentPopupData.networkType

  currentPopupObj.currentPopupData = currentPopupAsyncObj.data;

  // 获取完数据后进行弹窗
  callback(currentPopupObj.currentPopupData);
});

/**
 * 业务相关
 */
// 获取网络制式
mittBus.on("getContactType", (val) => {
  // console.log("获取网络制式", val, myOlMap, refOpenlayerBaseMap.value)

  if (refOpenlayerBaseMap.value) {
    currentContactType = val;
    reflashCurrentMapByType(); // 根据类型刷新当前可视区域地图
  }
});
// 查询基站类型
mittBus.on("getSerious", (val) => {
  // console.log("查询基站类型", val, myOlMap)

  if (refOpenlayerBaseMap.value) {
    currentSerious = val;
    reflashCurrentMapByType(); // 根据类型刷新当前可视区域地图
  }
});
// 切换渲染方式
mittBus.on("setRenderType", (val) => {
  // console.log("切换渲染方式", val, myOlMap);

  if (refOpenlayerBaseMap.value) {

    currentRenderType = val;

    reflashCurrentMapByType();
  }
});
// 加载kml
mittBus.on("loadKML", (text) => {
  // console.log('加载kml', text, myOlMap)

  if (refOpenlayerBaseMap.value) {

    refOpenlayerBaseMap.value.loadKML(myOlMap, text);

    // 加载当前4g5g
    currentSerious = undefined;
    currentContactType = "all";
    isRemoveMap.value = false;
    reflashCurrentMapByType(); // 根据类型刷新当前可视区域地图

    // 通知弹窗关闭
    mittBus.emit("closeLoadKfmlFileDialog");
  }
});

/**
 * 图层管理
 */
// 选择默认图层
mittBus.on("selectDefaultLayer", (val) => {
  // console.log("selectDefaultLayer", val)
  if (refOpenlayerBaseMap.value) {

    currentSerious = undefined;
    let currentType = "";

    if (val.length === 0) {
      refOpenlayerBaseMap.value.removeAllLayer(myOlMap); // 移除所有图层
    }

    if (val.length === 1) {
      switch (val[0]) {
        case "LTE资源":
          currentType = "4g";
          break;
        case "5G资源":
          currentType = "5g";
          break;
      }
      currentContactType = currentType;
      reflashCurrentMapByType();
    }

    if (val.length === 2) {
      currentContactType = "all";
      reflashCurrentMapByType();
    }

  }
});

/**
 * 网格管理
 */
// 选择网格
mittBus.on("selectGrid", (gridData) => {
  if (refOpenlayerBaseMap.value) {
    // console.log(gridData);
    let { centerCoordinates, polygonCoordinates } = gridData;
    // console.log(centerCoordinates, centerCoordinates);

    myOlMap.getView().setZoom(myOlMap.getView().getMinZoom()); // 修改至最小zoom

    refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "grid"); // 根据类型移除图层

    // 调用函数飞到指定的坐标
    refOpenlayerBaseMap.value.flyToCoordinate(myOlMap, centerCoordinates);

    let coords = polygonCoordinates.map((item) => {
      return refOpenlayerBaseMap.value.transformToPixelPoint(item[0], item[1]);
    });

    // 创建多边形
    refOpenlayerBaseMap.value.createPolygon(myOlMap, { coords, lonlat: polygonCoordinates, polygonData: gridData }, { businessType: 'grid' }, (feature) => {
      // console.log("创建多边形后操作", feature);

      let polygonCenter = refOpenlayerBaseMap.value.getPolygonCenter(feature);
      gridData.polygonCenter = polygonCenter;

      refOpenlayerBaseMap.value.addTextPoint(myOlMap, gridData.name, gridData.polygonCenter, { businessType: 'gridLabel' }, currentFeature => {
        // console.log(currentFeature)

        return currentFeature.get('businessType') === 'gridLabel'
      });
    },
      refOpenlayerBaseMap.value.setFeaturesStyle(
        "rgba(255, 255, 255, 0.8)",
        "#e4e7ed"
      ))
  }
});

/**
 * gisSubmit循环派发事件
 * 
 * 需要下拉检索的,直接store获取数据
 * 不需要下拉检索的,需要走接口,根据输入内容进行查询
 */
// 根据cgi搜索
mittBus.on("searchByCGI", cgi => {
  // console.log('根据cgi搜索', cgi)

  searchByCGIAsync(cgi); // 根据cgi搜索详情
});
// 根据经纬度搜索
mittBus.on("searchByLonlat", lonlat => {
  if (refOpenlayerBaseMap.value) {
    lonlat = lonlat.replace(/\s+/g, '');

    const regex = /^-?\d+(\.\d+)?,\s*-?\d+(\.\d+)?$/;

    if (!regex.test(lonlat)) {
      proxy.$modal.msgWarning(`经纬度格式错误`);
      return
    }

    const lonlatArr = lonlat.split(',')

    let tempArr = []
    allCurrentData.forEach(item => {
      if ((item.longitude.toString() === lonlatArr[0]) && (item.latitude.toString() === lonlatArr[1])) {
        tempArr.push(item)
      }
    })

    if (tempArr.length === 0) {
      proxy.$modal.msgWarning(`当前区域未查询到数据`);
      return
    }

    if (tempArr.length === 1) {
      searchByCGIAsync(tempArr[0].cgi); // 根据cgi搜索详情
    }

    if (tempArr.length > 1) {
      // console.log('有重叠元素', [lonlatArr[0], lonlatArr[1]])

      let itemData = {
        longitude: lonlatArr[0],
        latitude: lonlatArr[1],
        arrData: tempArr
      }

      // setMapByAutoPopupData
      refOpenlayerBaseMap.value.setMapByAutoPopupData(
        myOlMap,
        itemData,
        null,
        (olMap, dataList) => {
          renderFeatureByData(olMap, dataList[0].arrData);
        }
      );
    }
  }
});
// 根据小区名称搜索
mittBus.on("searchByCellName", () => {
  // console.log('根据小区名称搜索')

  let gisData = gisStoreData.gisSearchData

  // 如果只有一条数据
  if (gisData.length === 1) {
    searchByCGIAsync(gisData[0].cgi); // 根据cgi搜索详情
  }
});
// POI搜索
mittBus.on("POISearch", () => {
  // console.log('POI搜索1', gisStoreData.gisSearchData)

  setPoiPoint(gisStoreData.gisSearchData)  // 添加poi点
})
// 搜索框下拉选择
mittBus.on("selectGisSearchSubmit", (val) => {
  if (val.searchType === 'POI') {
    // console.log('POI搜索', val)

    setPoiPoint([val])  // 添加poi点
  } else {
    // console.log('业务搜索', val)
    searchByCGIAsync(val.cgi); // 根据cgi搜索详情
  }
});

/**
 * 业务
 */
// 显示隐藏概览
const toggleOverviewInfo = (val) => {
  // console.log('显示隐藏概览', val)

  isShowHealthOverview.value = val
}

/**
 * 扩展地图封装方法
 */
// 根据频率渲染扇形
const renderCurveByFrequency = (curveData, optity = 0.4) => {
  // console.log("根据频率渲染扇形");

  let myCurveStyle = null; // 扇区样式
  let myStrokeColor = "rgba(255, 205, 67, 0.3)";
  let myCurveRadius = 0; // 扇区半径

  /**
   * 根据频率获取数据
   *
   * A频段  100  填充: rgba(200, 22, 100, 0.4)   线:
   * D频段  110  填充: rgba(55, 33, 188, 0.4)   线:
   * E频段  120  填充: rgba(88, 99, 200, 0.4)   线:
   * F频段  130  填充: rgba(255, 255, 0, 0.4)   线:
   * FDD  140   填充:  rgba(255, 76, 127, 0.4)  线:
   * 其他  150  填充:  rgba(32, 222, 230, 0.4)   线 : rgba(255, 205, 67, 0.3)
   */
  switch (curveData.workFrequency) {
    case "A频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(200, 22, 100, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 100;
      break;
    case "D频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(55, 33, 188, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 110;
      break;
    case "E频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(88, 99, 200, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 120;
      break;
    case "F频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 255, 0, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 130;
      break;
    case "FDD":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 76, 127, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 140;
      break;
    default:
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(32, 222, 230, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 150;
      break;
  }

  return { myCurveStyle, myCurveRadius };
};

// 根据健康度渲染扇形
const renderCurveByHealth = (curveData, optity = 0.4) => {
  // console.log("根据健康度渲染扇形");

  let myCurveStyle = null; // 扇区样式
  let myStrokeColor = "rgba(255, 205, 67, 0.3)";
  let myCurveRadius = 0; // 扇区半径

  /**
   * 根据频率获取数据
   *
   * A频段  100  填充: rgba(200, 22, 100, 0.4)   线:
   * D频段  110  填充: rgba(55, 33, 188, 0.4)   线:
   * E频段  120  填充: rgba(88, 99, 200, 0.4)   线:
   * F频段  130  填充: rgba(255, 255, 0, 0.4)   线:
   * FDD  140   填充:  rgba(255, 76, 127, 0.4)  线:
   * 其他  150  填充:  rgba(32, 222, 230, 0.4)   线 : rgba(255, 205, 67, 0.3)
   */
  switch (curveData.workFrequency) {
    case "A频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(200, 22, 100, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 100;
      break;
    case "D频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(55, 33, 188, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 110;
      break;
    case "E频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(88, 99, 200, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 120;
      break;
    case "F频段":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 255, 0, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 130;
      break;
    case "FDD":
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(255, 76, 127, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 140;
      break;
    default:
      myCurveStyle = refOpenlayerBaseMap.value.setFeaturesStyle(
        `rgba(32, 222, 230, ${optity})`,
        myStrokeColor
      );
      myCurveRadius = 150;
      break;
  }

  return { myCurveStyle, myCurveRadius };
};

// 根据字段渲染扇形
const renderCurveByField = (curveData, optity = 0.4) => {
  switch (currentRenderType) {
    case "频率":
      return renderCurveByFrequency(curveData, (optity = 0.4));
    case "健康度":
      return renderCurveByHealth(curveData, (optity = 0.4));
  }
};

// 根据数据渲染Feature
const renderFeatureByData = (olMap, dataList) => {
  // console.log("根据数据渲染Feature", dataList);
  refOpenlayerBaseMap.value.renderFeatureByData(
    olMap,
    dataList,
    (olMap, item) => {
      refOpenlayerBaseMap.value.addPoint(olMap, {
        lonlat: [item.longitude, item.latitude],
        pointData: item,
      }, alarmPoint, { businessType: 'alarmPointMarker' });
    }
  );
};

// 通过单条数据设置地图
const setMapByAutoPopupData = (olMap, itemData) => {
  // console.log('通过单条数据设置地图', olMap, itemData)

  refOpenlayerBaseMap.value.setMapByAutoPopupData(
    olMap,
    itemData,
    (itemData) => {
      switch (itemData.networkType) {
        case "4g":
          itemData.newCellName = itemData.cellName;
          break;
        case "5g":
          itemData.newCellName = itemData.nrCellName;
          break;
      }
    },
    (olMap, dataList) => {
      renderFeatureByData(olMap, dataList);
    }
  );
};

// 添加POI点
/* const setPoiPoint = (POIDataList) => {
  let POIPointData = []

  POIDataList.forEach(item => {
    let lonlatArr = item.lonlat.split(',')
    POIPointData.push({
      lonlat: [parseFloat(lonlatArr[0]), parseFloat(lonlatArr[1])],
      pointData: item,
    });
  })

  refOpenlayerBaseMap.value.removeLayerByBusinessType(myOlMap, "POIMarker"); // 根据类型移除图层

  refOpenlayerBaseMap.value.addPoint(
    myOlMap,
    POIPointData,
    POIPoint,
    { businessType: 'POIMarker' }
  );
} */

/**
 * 封装工具
 */
// gis通用接口封装
const gisDataAsync = async (params, next, isMerge) => {
  proxy.$modal.loading("正在请求中，请稍候...");

  let gisData = await apiCommon(gisApi.queryRealTimeAlarmGisList, params);
  gisData = gisData.data;

  gisData.forEach((item) => {
    item.eventTime = formatDate(item.eventTime);
    switch (item.networkType) {
      case "103":
        item.networkType = "4g";
        break;
      case "108":
        item.networkType = "5g";
        break;
      case "101":
        item.networkType = "2g";
        break;
    }
  });

  if (isMerge) {
    next([...gisData.cell4gList, ...gisData.cell4gList]);
  } else {
    next(gisData);
  }

  proxy.$modal.closeLoading();
};

// 获取可视区域坐标参数
const getCurrentPositionParams = (olMap) => {
  // console.log("获取可视区域的左上角和右下角坐标", refOpenlayerBaseMap.value);

  let viewPosition = refOpenlayerBaseMap.value.getCurrentViewPosition(olMap);

  return {
    minLatitude: viewPosition.bottomRight[1],
    maxLatitude: viewPosition.topLeft[1],
    minLongitude: viewPosition.topLeft[0],
    maxLongitude: viewPosition.bottomRight[0],
  };
};

// 根据cgi搜索详情
const searchByCGIAsync = async (cgi) => {
  let params = {
    cgi,
  };

  let gisData = await apiCommon(gisApi.queryCellByCgi, params);

  if (!gisData.data) {
    // console.log(gisData.msg);
    proxy.$modal.msgError(gisData.msg);
  } else {
    gisData = gisData.data;
    // console.log(gisData);
  }

  switch (gisData.networkType) {
    case "4g":
      gisData.cell4g.networkType = "4g";
      setMapByAutoPopupData(myOlMap, gisData.cell4g);
      break;
    case "5g":
      gisData.cell5g.networkType = "5g";
      setMapByAutoPopupData(myOlMap, gisData.cell5g);
      break;
  }
};

// 根据类型刷新当前可视区域地图
const reflashCurrentMapByType = (setSingleData) => {
  // console.log("44422", currentContactType, currentSerious);

  if (myOlMap.getView().getZoom() < myMapCommonData.minRenderZoom) {
    proxy.$modal.msgWarning(
      `为减少卡顿,请在缩放等级大于等于${myMapCommonData.minRenderZoom}的时候进行刷新`
    );
    return;
  }

  let params = {
    ...getCurrentPositionParams(myOlMap),
    networkType: currentContactType,
    coverType: currentSerious === "all" ? undefined : currentSerious,
  };
  // console.log(params)

  getCurrentViewData(myOlMap)

  if (setSingleData) {
    // 设置被选中的单条数据
    setSingleData();
  }
};

/**
 * 业务方法
 */
// 获取地图实例 - 地图加载完初始化做的一些操作[业务相关]
const getOlMapInstance = (olMap, mapCommonData) => {
  // console.log("获取地图实例 - 地图加载完初始化做的一些操作[业务相关]", olMap);

  if (olMap.getView().getZoom() < mapCommonData.minRenderZoom) {
    /* proxy.$modal.msgWarning(
      `为减少卡顿,请在缩放等级大于等于${myMapCommonData.minRenderZoom}的时候进行刷新`
    );
    return; */
    olMap.getView().setZoom(16)
    olMap.getView().setCenter(fromLonLat([121.63, 29.88]))
  }

  // console.log(olMap, mapCommonData);

  myOlMap = olMap; // 赋值全局变量,为后续业务操作做准备

  myMapCommonData = mapCommonData;

  // 接收路由跳转参数
  getQuery();
};

// 获取可视区域数据 (主入口)
const getCurrentViewData = (olMap) => {
  let params = {
    ...getCurrentPositionParams(olMap),
    networkType: currentContactType === 'all' ? undefined : currentContactType,
    serious: currentSerious === 'all' ? undefined : currentSerious,
  };
  // console.log(params);

  gisDataAsync(params, (gisDataList) => {
    // console.log(gisDataList);

    renderFeatureByData(olMap, gisDataList);
  });
};

// 刷新地图 - 主入口方法
const reflashMap = (resetFlag, next) => {
  // console.log("刷新地图", resetFlag);

  // 根据类型刷新当前可视区域地图
  reflashCurrentMapByType(() => {
    // 如果刷新后需要进行其他操作
    if (next) {
      next();
    }
  });
};

onUnmounted(() => {
  // console.log('onUnmounted')

  mittBus.all.delete('popupDataGetMore')
})
</script>

<style lang="scss" scoped>
.alarm_gis_map {
  :deep .ol_map {
    .ol-popup {
      .popup_wrap {
        height: 182px;
      }
    }
  }
}
</style>